package lib

import (
	"crypto/md5"
	"fmt"
	"io"
	"math/rand"
	"regexp"
	"sort"
	"strings"
	"sync"
	"time"
)

var (
	muRand      sync.Mutex
	seRand      = rand.New(rand.NewSource(time.Now().UnixNano()))
	letterRunes = []rune("1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
)

/*
 * 描述: MD5生成32位小写哈希值
 *
 ***************************************************************************/
func StrMd5Str(strPass string) string {
	w := md5.New()
	io.WriteString(w, strPass)
	return fmt.Sprintf("%x", w.Sum(nil))
}

//按照字符排序，从小到大
func StrSort(str string) string {
	split := strings.Split(str, "")
	sort.Strings(split)
	resStr := ""
	for _, v := range split {
		resStr += v
	}
	return resStr
}

/*
 * 描述: MD5生成32位大写哈希值
 *
 ***************************************************************************/
func StrMd5STR(str string) string {
	w := md5.New()
	io.WriteString(w, str)
	return fmt.Sprintf("%X", w.Sum(nil))
}

/*
 * 描述: 手机号识别
 *
 ***************************************************************************/
func IsPhone(strPhone string) bool {
	regular := "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0-9])|(19[0-9])|(17[0-9]))\\d{8}$"
	reg := regexp.MustCompile(regular)
	return reg.MatchString(strPhone)
}

/*
 * 描述: 身份证识别
 *
 ***************************************************************************/
func IsNumberId(number_id string) bool {
	regular := "^((1[1-5])|(2[1-3])|(3[1-7])|(4[1-6])|(5[0-4])|(6[1-5])|71|(8[12])|91)\\d{4}((19\\d{2}(0[13-9]|1[012])(0[1-9]|[12]\\d|30))|(19\\d{2}(0[13578]|1[02])31)|(19\\d{2}02(0[1-9]|1\\d|2[0-8]))|(19([13579][26]|[2468][048]|0[48])0229))\\d{3}(\\d|X|x)?$"
	reg := regexp.MustCompile(regular)
	return reg.MatchString(number_id)
}

func RandNum(nMin, nMax int) int {
	for i := 0; i < 20; i++ {
		rand.Seed(time.Now().Unix())
		rnd := rand.Intn(nMax)
		if rnd > nMin {
			return rnd
		}
	}
	return int(nMin + ((nMax - nMin) / 2))
}

func IsIdCard(idCard string) (res bool, err error) {
	res, err = regexp.Match("^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$|^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$", []byte(idCard))
	return res, err
}

/*
 * 描述: 随机数/字符
 *
 ***************************************************************************/
func RandStrs(num int) string { // 1-0 and a - Z
	b := make([]rune, num)

	for i := range b {
		b[i] = letterRunes[RandInt(len(letterRunes))]
	}
	return string(b)
}
func RandInt(max int) int {
	if max <= 0 {
		return 0
	}
	defer UnLock(Lock(&muRand))
	value := seRand.Int()
	return value % max
}
func UnLock(lockFun *sync.Mutex) { lockFun.Unlock() }

/*
 * 描述: 半自动锁
 *
 ***************************************************************************/
func Lock(mu *sync.Mutex) *sync.Mutex { mu.Lock(); return mu }

//切片内数组去重

func DeleteDuplicateValue(s []int) (ret []int) {

	tmpM := make(map[int]int) // key的类型要和切片中的数据类型一致
	for _, v := range s {
		tmpM[v] = 1
	}
	// 先清空s
	s = []int{}
	for i, _ := range tmpM {
		s = append(s, i)
	}
	return s
}
